package com.future.service.impl;

import com.future.cons.Const;
import com.future.service.TradeService;
import com.future.vo.Stock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

/**
 * Description:
 *
 * @author weiruibai.vendor
 * Date: 2022/9/19 15:01
 */
@Service
@Qualifier(value = "redisReceiver")
public class RedisReceiver extends CommonService implements TradeService {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisReceiver.class);

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void receiveMessage(String message) {
        LOGGER.info("order: {}", message);
        lock();
    }

    @Override
    public String lock() {
        SessionCallback sessionCallback = new SessionCallback() {
            Object oldTicketSum = redisTemplate.opsForValue().get(Const.TICKET_SUM);

            @Override
            @SuppressWarnings("unchecked")
            public Object execute(RedisOperations operations) throws DataAccessException {
                //operations.watch(Const.TICKET_SUM);
                operations.multi();
                Integer ticket;
                if (oldTicketSum == null || (ticket = Integer.parseInt(oldTicketSum + "")) < 1) {
                    Stock select = select(1);
                    if (null != select && select.getStock() >= 1) {
                        ticket = select.getStock();
                    } else {
                        LOGGER.error("票数为空，停止抢票");
                        return null;
                    }
                }
                LOGGER.info("ticketSum: {}", ticket);
                operations.opsForValue().set(Const.TICKET_SUM, ticket - 1);
                doDBUpdate(ticket - 1);
                return operations.exec();
            }
        };
        redisTemplate.execute(sessionCallback);
        return null;
    }
}
